package com.graduation.project.filter;

import cn.hutool.jwt.JWT;
import com.graduation.project.entity.other.LoginUser;
import com.graduation.project.utils.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 卑微小峰
 * @date 2022/11/16
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 没有token，放行,交给后面的过滤器去判断是否是认证的状态
            filterChain.doFilter(request, response);
            return;
        }

//        // 验证token
//        JWTValidator jwtValidator = JWTValidator.of(token)
//                // 1、验证算法
//                .validateAlgorithm(JWTSignerUtil.hs256(ConstantPool.JWT_KEY.getBytes()))
//                // 2、验证时间
//                .validateDate(DateUtil.parse("2022-10-10 00:00:00"));


        // 解析token
        JWT jwt = JWT.of(token);
        String userCode = (String) jwt.getPayload("userCode");

        // 从Redis中获取用户信息
        String redisKey = "login:" + userCode;
        LoginUser loginUser = redisCacheUtil.getCacheObject(redisKey);
        if (ObjectUtils.isEmpty(loginUser)) {
            throw new RuntimeException("用户未登录");
        }

        // 存入SecurityContextHolder中（因为后面其他的filter要从这里获取信息判断是否已经认证过了）
        // 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}
